import store from '@/store'
import { intersection } from 'lodash'

const hasPermission = {
  install (Vue, options) {
    // console.log(options)
    Vue.directive('has', {
      inserted: (el, binding, vnode) => {
        // console.log('load btn')
        let { value } = binding

        if (value) {
          value = value instanceof Array ? value : [value]
          if (!hasPermissions(value)) {
            el.parentNode && el.parentNode.removeChild(el)
          }
        } else {
          throw new Error(`need btn! Like v-has="['system:menu:list']"`)
        }
      }
    })
  }
}

export function hasPermissions (permissions) {
  const needPermissions = permissions || []

  let permissionList = store.getters && store.getters.permissionList

  if (permissionList.length === 0) return false

  if (permissionList.includes('*:*:*')) return true

  // 判断用户是否拥有可以访问的权限
  const mergePermissions = intersection(needPermissions, permissionList)

  // 如果没有，则验证不通过
  return !!mergePermissions.length
}

export default hasPermission
